<template>
  <a-card class="general-card" title="店铺分类" :bordered="false">
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="addParent"> 添加一级分类 </a-button>
        </a-space>
      </a-col>
    </a-row>
    <tablePage
      ref="tablePageRef"
      :data-list="labelData"
      :columns="columnsTable"
      :methods="sortMethods"
      :enable-pagination="false"
      :checkbox="isNormal ? false : true"
      :radio="isNormal ? false : true"
      @delete="remove"
      @selectTableChange="chosenCategory"
    >
      <template #children="{ data }">
        {{ data.labelName }}
      </template>
      <template #editor="{ data }">
        <a-button type="text" status="warning" @click="edit(data)"
          >编辑</a-button
        >
      </template>
      <template #detailChildCategory="{ data }">
        <a-button v-if="data.level != 1" type="text" @click="addChildren(data)"
          >添加子分类</a-button
        >
        <div v-else style="width: 102px"></div>
      </template>
    </tablePage>
    <a-modal v-model:visible="visible" :width="500">
      <template #title> {{ modalTitle }} </template>
      <div>
        <a-form
          ref="formRef"
          :model="formAdd"
          :style="{ width: '400px' }"
          layout="horizontal"
          auto-label-width
        >
          <a-form-item
            v-if="showParent"
            field="parentId"
            :validate-trigger="['change', 'input']"
            label="上级分类"
          >
            {{ parentTitle }}
            <!-- <a-input
            v-model="formAdd.parentId"
            :style="{ width: '320px' }"
            allow-clear
            class="hideInput"
          /> -->
          </a-form-item>
          <a-form-item field="level" label="层级" style="display: none">
            <a-input v-model="formAdd.level" />
          </a-form-item>
          <a-form-item field="labelName" label="分类名称" :rules="[REQUIRED]">
            <a-input v-model="formAdd.labelName" />
          </a-form-item>
          <a-form-item field="sortOrder" label="排序值" :rules="[REQUIRED]">
            <a-input-number
              v-model="formAdd.sortOrder"
              :style="{ width: '320px' }"
              class="input-demo"
              :min="1"
              :max="999"
            />
          </a-form-item>
        </a-form>
      </div>
      <template #footer>
        <div style="text-align: right">
          <a-button style="margin-right: 5px" @click="clearForm">取消</a-button>
          <a-button type="primary" :loading="loading" @click="handleSubmit">提交</a-button>
        </div>
      </template>
    </a-modal>
  </a-card>
</template>

<script setup lang="ts">
  import {
addShopGoodsLabel,
delCateShopGoodsLabel,
editShopGoodsLabel,
getLabelData,
} from '@/api/goods';
import tablePage from '@/components/table-pages/index.vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { ColumnsDataRule, MethodsRule } from '@/types/global';
import { REQUIRED } from '@/utils/validator';
import { Message } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { onMounted, ref } from 'vue';
  // 组件模式
  const props = defineProps({
    templateModel: {
      type: String,
      default: 'normal',
    },
  })
  const loading = ref<boolean>(false);
  const flatTableList = ref<Array<any>>([]);
  const isNormal: boolean = props.templateModel === 'normal';
  const emit = defineEmits(['selectTableChange'])
  // 获取modal
  const modal = useCurrentInstance().globalProperties?.$modal;
  const parentTitle = ref<string>('');
  const modalTitle = ref<string>(''); // 弹框标题
  const showParent = ref(false); // 是否展示标题
  const visible = ref(false);
  const tablePageRef = ref<any>('');
  const formRef = ref<FormInstance>() as any;
  const modalType = ref<number>(0); // 编辑/添加
  interface formInterface {
    parentId: string | number;
    level: string | number;
    image: string;
    isRead?: string;
    sortOrder: number;
    commissionRate: number;
    deleteFlag: string | number;
    [key: string]: any;
  }
  const formAdd = ref<formInterface>({
    parentId: 0,
    level: 0,
    image: '',
    sortOrder: 1,
    commissionRate: 0,
    deleteFlag: '0',
    name: '',
    id: '',
  }) as any;
  const columnsTable: ColumnsDataRule[] = [
    {
      title: '分类名称',
      dataIndex: 'id',
      width: 150,
      slot: true,
      slotTemplate: 'children',
    },
  ];
  const labelData = ref<any>([]);

  // 获取分类数据
  const getData = () => {
    getLabelData().then((res) => {
      if (res.data.success) {
        if(res.data.result.length){
        const loop = (data:any) => {
          const result:Array<any> = [];
          data.forEach((item:any) => {
            if (item.children && item.children.length) {
              const filterData = loop(item.children);
              result.push({...item, children: filterData});
            } else {
              result.push({...item, children: null});
            }
            flatTableList.value.push(item);
          });
          return result;
        };
        labelData.value = loop(res.data.result) ;
      }
      }
      console.log("flatTableList",flatTableList.value)
    });
  };

  const sortMethods: MethodsRule = {
    title: '操作',
    width: 250,
    fixed: 'right',
    methods: [
      {
        title: '添加子分类',
        callback: 'detailChildCategory',
        slot: true,
        slotTemplate: 'detailChildCategory',
      },
      {
        title: '编辑',
        callback: 'editor',
        slot: true,
        slotTemplate: 'editor',
      },
      {
        title: '删除',
        callback: 'delete',
        type: 'text',
        status: 'danger',
      },
    ],
  };
  // 添加一级分类
  const addParent = () => {
    modalType.value = 0;
    parentTitle.value = ' 顶级分类 ';
    modalTitle.value = ' 添加一级分类 ';
    showParent.value = true;
    visible.value = true;
  };
  // 编辑分类
  const edit = (v: any) => {
    modalType.value = 1;
    modalTitle.value = ' 编辑 ';
    showParent.value = false;
    formAdd.value.id = v.id;
    formAdd.value.labelName = v.labelName;
    formAdd.value.level = v.level;
    formAdd.value.parentId = v.parentId || 0;
    formAdd.value.sortOrder = v.sortOrder;
    visible.value = true;
  };
  // 清空表单
  const clearForm = () => {
    formRef.value.resetFields();
    visible.value = false;
  };
  // 添加子分类
  const addChildren = (data: any) => {
    modalType.value = 0;
    parentTitle.value = data.labelName;
    modalTitle.value = ' 添加子分类 ';
    formAdd.value.level = data.level + 1;
    formAdd.value.labelName = '';
    delete formAdd.value.id;
    formAdd.value.parentId = data.id;
    showParent.value = true;
    visible.value = true;
  };
  // 删除
  const remove = (data: any) => {
    modal.confirm({
      title: '确认删除',
      content: `您确认要删除${data.record.labelName}?`,
      onOk: async () => {
        const res = await delCateShopGoodsLabel(data.record.id);
        if (res.data.success) {
          Message.success('删除成功！');
          // tablePageRef.value.init()
          getData();
        }
      },
    });
  };
  // 提交
  const handleSubmit = async () => {
    loading.value = true;
    // const auth = await formRef.value?.validate();
    // if (!auth) {
    if (modalType.value == 0) {
      addShopGoodsLabel(formAdd.value).then((res: any) => {
        loading.value = false
        if (res.data.code == 200) {
          Message.success('添加成功');
          clearForm();
          getData();
          tablePageRef.value.init();
        }
      });
    } else {
      editShopGoodsLabel(formAdd.value).then((res: any) => {
        loading.value = false
        if (res.data.code == 200) {
          Message.success('修改成功');
          clearForm();
          // tablePageRef.value.init();
          getData();
        }
      });
    }
    // }
  };
    // 选择商品分类
    function chosenCategory(val: any) {
    const data = flatTableList.value.find((item:any)=> item.id === val[0])
    emit('selectTableChange', { ...data, name:data.labelName, ___type: 'category' })
  }

  onMounted(() => {
    getData();
  });
</script>
